// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//
#include <pollux/common/config/config.h>
#include <pollux/common/file/file.h>
#include <pollux/connectors/hive/storage_adapters/gcs/gcs_file_system.h>

#include <melon/init/init.h>
#include <turbo/flags/flag.h>
#include <iostream>

TURBO_FLAG(std::string,gcs_path, "", "Path of GCS bucket");
TURBO_FLAG(std::string,gcs_max_retry_count, "", "Max retry count");
TURBO_FLAG(std::string,gcs_max_retry_time, "", "Max retry time");

auto newConfiguration() {
    using namespace kumo::pollux;
    melon::F14FastMap<std::string, std::string> configOverride = {};
    if (!FLAGS_gcs_max_retry_count.empty()) {
        configOverride.emplace(
            "hive.gcs.max-retry-count", FLAGS_gcs_max_retry_count);
    }
    if (!FLAGS_gcs_max_retry_time.empty()) {
        configOverride.emplace("hive.gcs.max-retry-time", FLAGS_gcs_max_retry_time);
    }
    return std::make_shared<const config::ConfigBase>(std::move(configOverride));
}

int main(int argc, char **argv) {
    using namespace kumo::pollux;
    gflags::ParseCommandLineFlags(&argc, &argv, false);
    if (FLAGS_gcs_path.empty()) {
        gflags::ShowUsageWithFlags(argv[0]);
        return 1;
    }
    filesystems::GcsFileSystem gcfs(newConfiguration());
    gcfs.initializeClient();
    std::cout << "Opening file for read " << FLAGS_gcs_path << std::endl;
    std::unique_ptr<ReadFile> file_read = gcfs.openFileForRead(FLAGS_gcs_path);
    std::size_t file_size = file_read->size();
    std::cout << "File size = " << file_size << std::endl;
    std::string buffer(file_size + 1, '\0');
    file_read->pread(0 /*offset*/, file_size /*lenght*/, buffer.data());
    std::cout << "File Content = " << buffer << std::endl;
}
